package com.weixin.location;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.gson.Gson;
import com.weixin.location.adapter.SearchAddressAdapter;
import com.weixin.location.utils.DatasKey;
import com.weixin.location.utils.OnItemClickLisenter;
import com.weixin.location.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 位置搜索Activity
 */
public class MapSearchActivity extends AppCompatActivity {

    private ImageView imageView;
    private EditText edtSearch;
    private RecyclerView recyclerView;
    private List<PoiItem> poiItems;
    private SearchAddressAdapter searchAddressAdapter;

    private PoiSearch poiSearch;
    private PoiSearch.Query query;
    private PoiSearch.OnPoiSearchListener onPoiSearchListener;

    private View.OnClickListener onClickListener;
    private OnItemClickLisenter onItemClickLisenter;

    private Gson gson;
    public AMapLocation location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_search);
        initView();
        initDatas();
        initListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null == location) {
            String s = SPUtils.getString(this, DatasKey.LOCATION_INFO);//获取保存的定位信息
            if (!TextUtils.isEmpty(s)) {
                try {
                    location = gson.fromJson(s, AMapLocation.class);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != poiSearch) {
            poiSearch = null;
        }
    }

    private void initView() {
        imageView = (ImageView) findViewById(R.id.imgBack);
        edtSearch = (EditText) findViewById(R.id.edtSearch);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    }

    private void initDatas() {
        poiItems = new ArrayList<>();
        searchAddressAdapter = new SearchAddressAdapter(this, poiItems);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(searchAddressAdapter);

        gson = new Gson();
    }

    private void initListener() {

        onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.imgBack:
                        finish();
                        break;
                }
            }
        };
        imageView.setOnClickListener(onClickListener);

        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (null != editable) {
                    if (0 == editable.length()) {//没有输入则清空搜索记录
                        poiItems.clear();
                        searchAddressAdapter.setList(poiItems, "");
                    } else {
                        if (null != location) {
                            doSearchQuery(editable.toString(), location.getCity(), new LatLonPoint(location.getLatitude(), location.getLongitude()));
                        } else {
                            doSearchQuery(editable.toString(), "", null);
                        }
                    }
                }
            }
        });

        onItemClickLisenter = new OnItemClickLisenter() {
            @Override
            public void onItemClick(int position) {
                PoiItem poiItem = poiItems.get(position);
                if (null != poiItem) {//获取信息并回传上一页面
                    Intent intent = new Intent();
                    intent.putExtra(DatasKey.SEARCH_INFO, poiItem);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        };
        searchAddressAdapter.setOnItemClickLisenter(onItemClickLisenter);

        onPoiSearchListener = new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult result, int i) {
                if (i == 1000) {
                    if (result != null && result.getQuery() != null) {// 搜索poi的结果
                        if (result.getQuery().equals(query)) {// 是否是同一条
                            if (null != poiItems) {
                                poiItems.clear();
                            }
                            poiItems.addAll(result.getPois());// 取得第一页的poiitem数据，页数从数字0开始
                            if (null != searchAddressAdapter) {
                                searchAddressAdapter.setList(poiItems, edtSearch.getText().toString().trim());
                                recyclerView.smoothScrollToPosition(0);
                            }
                        }
                    }
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        };

    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String keyWord, String city, LatLonPoint lpTemp) {
        query = new PoiSearch.Query(keyWord, "", city);//第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);// 设置查第一页


        //在构造PoiSearch之前必须进行合规检查（RouteSearch，WeatherSearch等也是一样的操作），设置接口之前保证隐私政策合规
        ServiceSettings.updatePrivacyShow(this,true,true);
        ServiceSettings.updatePrivacyAgree(this,true);

        try {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(onPoiSearchListener);
            if (lpTemp != null) {
                poiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 3000, true));//该范围的中心点-----半径，单位：米-----是否按照距离排序
            }
            poiSearch.searchPOIAsyn();// 异步搜索
        } catch (AMapException e) {
            e.printStackTrace();
        }
    }

}
